package com.xgj.filter;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器使用：所有请求都过滤
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化....");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();

        // 放行特定接口
        if ("/api/random-users/import".equals(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        // 以下是原有的处理逻辑
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestUrl = httpRequest.getRequestURL().toString();
        String method = httpRequest.getMethod();
        System.out.printf("[Filter] %s %s | Start%n", method, requestUrl);

        long startTime = System.currentTimeMillis();
        try {
            chain.doFilter(request, response);
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            System.out.printf("[Filter] %s %s | End | Status: %d | Time: %dms%n",
                    method, requestUrl, httpResponse.getStatus(), duration);
        }
    }

    @Override
    public void destroy() {
        // 销毁操作
        System.out.println("过滤器销毁....");
    }
}
